<template>
  <div class="student-grades">
    <TeacherNavbar title="学生考试成绩" />
    
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>学生成绩概览</span>
        </div>
      </template>
      
      <div class="stats-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon bg-blue">
                <i class="el-icon-user"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ studentGradesData.length }}</div>
                <div class="stat-label">学生总数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon bg-green">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalExams }}</div>
                <div class="stat-label">考试总数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon bg-orange">
                <i class="el-icon-star-off"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ averageScoreAll.toFixed(1) }}</div>
                <div class="stat-label">整体平均分</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon bg-purple">
                <i class="el-icon-trophy"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ highestScore }}</div>
                <div class="stat-label">最高分</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>详细成绩</span>
        </div>
      </template>
      
      <el-table :data="studentGradesData" style="width: 100%" v-loading="loading">
        <el-table-column type="expand">
          <template #default="props">
            <div class="exam-details">
              <h4>{{ props.row.username }} 的考试记录</h4>
              <el-table :data="props.row.exams" style="width: 100%; margin-top: 15px;">
                <el-table-column prop="subjectName" label="科目" width="150"></el-table-column>
                <el-table-column prop="score" label="得分" width="100">
                  <template #default="scope">
                    <span :class="getScoreClass(scope.row.score, scope.row.totalScore)">
                      {{ scope.row.score }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="totalScore" label="总分" width="100"></el-table-column>
                <el-table-column prop="examTime" label="考试时间" width="200"></el-table-column>
                <el-table-column label="得分率" width="150">
                  <template #default="scope">
                    <el-progress 
                      :percentage="calculatePercentage(scope.row.score, scope.row.totalScore)" 
                      :status="getProgressStatus(scope.row.score, scope.row.totalScore)"
                      :show-text="false"
                      :stroke-width="10">
                    </el-progress>
                    <span class="percentage-text">{{ calculatePercentage(scope.row.score, scope.row.totalScore) }}%</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="username" label="学生姓名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="examCount" label="考试次数" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.examCount > 0 ? 'primary' : 'info'">
              {{ scope.row.examCount }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="averageScore" label="平均分" width="100">
          <template #default="scope">
            <span :class="getAverageScoreClass(scope.row.averageScore)">
              {{ scope.row.averageScore }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import TeacherAPI from '@/api/teacher'
import TeacherNavbar from '@/components/TeacherNavbar.vue'

export default {
  name: 'StudentGrades',
  components: {
    TeacherNavbar
  },
  data() {
    return {
      loading: false,
      studentGrades: {}
    }
  },
  computed: {
    studentGradesData() {
      // 将后端返回的数据转换为表格可用的格式
      const result = []
      for (const userKey in this.studentGrades) {
        // 使用 Object.prototype.hasOwnProperty.call 替代 hasOwnProperty
        if (Object.prototype.hasOwnProperty.call(this.studentGrades, userKey)) {
          const exams = this.studentGrades[userKey]
          // 从userKey中提取用户名，格式如 "Users(id=6, username=hubery1, ...)"
          const usernameMatch = userKey.match(/username=([^,]+)/)
          const emailMatch = userKey.match(/email=([^,]+)/)
          
          const userData = {
            username: usernameMatch ? usernameMatch[1] : '未知用户',
            email: emailMatch ? emailMatch[1] : '未知邮箱',
            exams: exams,
            examCount: exams.length,
            averageScore: exams.length > 0 
              ? (exams.reduce((sum, exam) => sum + exam.score, 0) / exams.length).toFixed(2) 
              : 0
          }
          result.push(userData)
        }
      }
      return result
    },
    
    // 计算总考试次数
    totalExams() {
      return this.studentGradesData.reduce((total, student) => total + student.examCount, 0)
    },
    
    // 计算整体平均分
    averageScoreAll() {
      const allScores = this.studentGradesData.flatMap(student => 
        student.exams.map(exam => exam.score)
      )
      if (allScores.length === 0) return 0
      const sum = allScores.reduce((sum, score) => sum + score, 0)
      return sum / allScores.length
    },
    
    // 计算最高分
    highestScore() {
      const allScores = this.studentGradesData.flatMap(student => 
        student.exams.map(exam => exam.score)
      )
      if (allScores.length === 0) return 0
      return Math.max(...allScores)
    }
  },
  created() {
    this.fetchStudentGrades()
  },
  methods: {
    async fetchStudentGrades() {
      this.loading = true
      try {
        const res = await TeacherAPI.getStudentGrades()
        if (res.data.code === 200 && res.data.msg === 'success') {
          this.studentGrades = res.data.data
        } else {
          this.$message.error(res.data.message || '获取学生成绩失败')
        }
      } catch (error) {
        console.error('获取学生成绩失败:', error)
        this.$message.error('获取学生成绩失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },
    
    calculatePercentage(score, totalScore) {
      if (totalScore === 0) return 0
      return Math.round((score / totalScore) * 100)
    },
    
    getProgressStatus(score, totalScore) {
      if (totalScore === 0) return null
      const percentage = (score / totalScore) * 100
      if (percentage >= 80) return 'success'
      if (percentage >= 60) return 'warning'
      return 'exception'
    },
    
    // 获取分数的样式类
    getScoreClass(score, totalScore) {
      const percentage = (score / totalScore) * 100
      if (percentage >= 80) return 'score-excellent'
      if (percentage >= 60) return 'score-good'
      return 'score-poor'
    },
    
    // 获取平均分的样式类
    getAverageScoreClass(averageScore) {
      if (averageScore >= 80) return 'score-excellent'
      if (averageScore >= 60) return 'score-good'
      return 'score-poor'
    }
  }
}
</script>

<style scoped>
.student-grades {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 40px);
}

.search-card, .table-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: none;
}

.card-header {
  font-size: 1.3rem;
  font-weight: 500;
  color: #333;
  padding: 20px;
}

.stats-container {
  padding: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: #fff;
  font-size: 22px;
}

.bg-blue {
  background: #409eff;
}

.bg-green {
  background: #67c23a;
}

.bg-orange {
  background: #e6a23c;
}

.bg-purple {
  background: #926dde;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  color: #666;
}

.exam-details {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin: 10px;
}

.exam-details h4 {
  margin-top: 0;
  color: #333;
}

.percentage-text {
  margin-left: 10px;
  font-weight: 500;
  color: #666;
}

.score-excellent {
  color: #67c23a;
  font-weight: 600;
}

.score-good {
  color: #e6a23c;
  font-weight: 600;
}

.score-poor {
  color: #f56c6c;
  font-weight: 600;
}

@media (max-width: 768px) {
  .stats-container {
    padding: 10px;
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .stat-number {
    font-size: 1.5rem;
  }
}
</style>